"""
封装yaml文件操作
"""
import os
import yaml
from yaml import FullLoader
from pathlib import Path
from Common.tools import Tools
import jsonpath

class YamlOpertion():
        def __init__(self):
            self.tool=Tools()

        # 1.读取yaml文件数据
        def read_yaml(self,key=None,node1=None,node2=None,modulepath='Data', filepath=None, filename='extract.yml'):
            file_path=self.tool.get_filepath(modulepath=modulepath, filepath=filepath, filename=filename)

            with open(file_path,encoding='utf-8') as f:
                yaml_data=yaml.load(stream=f,Loader=FullLoader)

            if key !=None :
                # 返回jsonpath()结果的第一个值[0],因为jsonpath结果是一个列表
                return jsonpath.jsonpath(yaml_data,f"$..{key}")[0]
            elif node1 and node2:
                return yaml_data[node1][node2]
            elif node1 and node2==None:
                return yaml_data[node1]
            else:
                return yaml_data

        # 2.写入yaml文件数据
        def write_yaml(self,value,modulepath='Data', filepath=None, filename='extract.yml'):
            file_path = self.tool.get_filepath(modulepath=modulepath, filepath=filepath, filename=filename)

            if isinstance(value,dict):
                with open(file_path,mode='a+',encoding='utf-8') as f:
                    yaml.dump(data=value,stream=f,allow_unicode=True,encoding='utf-8')
            else:
                print('数据不为字典')

        def clean_yaml(self, value='', modulepath='Data', filepath=None, filename='extract.yml'):
            file_path = self.tool.get_filepath(modulepath=modulepath, filepath=filepath, filename=filename)

            with open(file_path, mode='w', encoding='utf-8') as f:
               f.write(value)

        # 3.解析用例基本信息并组合
        def analyse_case(self,modulepath='Data', filepath=None, filename='extract.yml'):
            file_path=self.tool.get_filepath(modulepath=modulepath, filepath=filepath, filename=filename)

            with open(file_path,encoding='utf-8') as f:
                yaml_data=yaml.load(stream=f,Loader=FullLoader)
            yaml_data=yaml_data[0]
            testcase_list=[]
            base_info=yaml_data['base_info']
            test_case=yaml_data['test_case']
            if len(test_case)>=1:
                for ts in test_case:
                    params=[base_info,ts]
                    testcase_list.append(params)
                return testcase_list
            else:
                return yaml_data


if __name__ == '__main__':
    yo=YamlOpertion()
    print(yo.analyse_case(filepath='Login',filename='login_data.yml'))